import React, { useState, useEffect } from 'react';
import { RoomStatusManager } from '../utils/RoomStatusManager';
import type { DragDropState } from '../hooks/useDragDrop';
import styles from '../styles/EnhancedDragPreview.module.css';

interface EnhancedDragPreviewProps {
  dragState: DragDropState;
  config: {
    cellWidth: number;
    cellHeight: number;
    dates: string[];
  };
}

const EnhancedDragPreview: React.FC<EnhancedDragPreviewProps> = ({
  dragState,
  config,
}) => {
  const [trail, setTrail] = useState<
    Array<{ x: number; y: number; timestamp: number }>
  >([]);
  const [isAnimating, setIsAnimating] = useState(false);

  // 更新拖拽轨迹
  useEffect(() => {
    if (dragState.isDragging && dragState.dragData) {
      const newPoint = {
        x: dragState.dragData.currentX,
        y: dragState.dragData.currentY,
        timestamp: Date.now(),
      };

      setTrail(prevTrail => {
        // 保留最近的8个点，创建轨迹效果
        const updatedTrail = [...prevTrail, newPoint].slice(-8);

        // 清理超过500ms的点
        const now = Date.now();
        return updatedTrail.filter(point => now - point.timestamp < 500);
      });
    } else {
      setTrail([]);
    }
  }, [
    dragState.isDragging,
    dragState.dragData?.currentX,
    dragState.dragData?.currentY,
  ]);

  // 拖拽完成动画
  useEffect(() => {
    if (!dragState.isDragging && trail.length > 0) {
      setIsAnimating(true);
      const timer = setTimeout(() => {
        setTrail([]);
        setIsAnimating(false);
      }, 300);

      return () => clearTimeout(timer);
    }
  }, [dragState.isDragging, trail.length]);

  if (!dragState.isDragging && !isAnimating) {
    return null;
  }

  const { dragData, dropTarget, canDrop } = dragState;

  if (!dragData) return null;

  const statusConfig = RoomStatusManager.getStatusConfig(dragData.sourceStatus);

  // 计算预览卡片位置
  const previewStyle = {
    left: `${dragData.currentX + dragData.offset.x}px`,
    top: `${dragData.currentY + dragData.offset.y}px`,
    width: `${config.cellWidth}px`,
    height: `${config.cellHeight}px`,
  };

  // 获取状态特定的样式
  const getStatusStyles = () => {
    return {
      backgroundColor: statusConfig.backgroundColor,
      borderColor: statusConfig.borderColor,
      color: statusConfig.color,
    };
  };

  // 获取拖拽状态的CSS类
  const getDragStateClass = () => {
    if (!canDrop) return styles.invalid;
    if (dropTarget?.isValid) return styles.valid;
    return styles.dragging;
  };

  return (
    <div className={styles.dragContainer}>
      {/* 拖拽轨迹 */}
      {trail.map((point, index) => (
        <div
          key={index}
          className={styles.trailPoint}
          style={{
            left: `${point.x + dragData.offset.x}px`,
            top: `${point.y + dragData.offset.y}px`,
            opacity: ((index + 1) / trail.length) * 0.6,
            transform: `scale(${(index + 1) / trail.length})`,
            animationDelay: `${index * 50}ms`,
          }}
        />
      ))}

      {/* 主拖拽预览卡片 */}
      <div
        className={`${styles.dragPreview} ${getDragStateClass()}`}
        style={{
          ...previewStyle,
          ...getStatusStyles(),
        }}
      >
        {/* 卡片内容 */}
        <div className={styles.previewContent}>
          <div className={styles.previewIcon}>{statusConfig.icon}</div>
          <div className={styles.previewText}>
            <div className={styles.roomNumber}>
              {dragData.sourceRoom.roomNumber}
            </div>
            <div className={styles.statusLabel}>{statusConfig.shortLabel}</div>
          </div>
        </div>

        {/* 状态指示器 */}
        <div className={styles.statusIndicator}>
          {canDrop ? (
            dropTarget?.isValid ? (
              <div className={styles.validIndicator}>✓</div>
            ) : (
              <div className={styles.pendingIndicator}>○</div>
            )
          ) : (
            <div className={styles.invalidIndicator}>✗</div>
          )}
        </div>

        {/* 脉冲边框 */}
        <div className={styles.pulseRing} />
      </div>

      {/* 目标位置预览 */}
      {dropTarget && canDrop && dropTarget.isValid && (
        <div className={styles.dropZonePreview}>
          <div className={styles.dropZoneAnimation}>
            <div className={styles.dropZoneRipple} />
            <div className={styles.dropZoneRipple} />
            <div className={styles.dropZoneRipple} />
          </div>
          <div className={styles.dropZoneText}>
            松开以移动到 {dropTarget.room.roomNumber}
          </div>
        </div>
      )}

      {/* 无效放置提示 */}
      {dropTarget && !dropTarget.isValid && (
        <div className={styles.invalidDropHint}>
          <div className={styles.invalidIcon}>🚫</div>
          <div className={styles.invalidText}>
            {dropTarget.reason || '无法移动到此位置'}
          </div>
        </div>
      )}

      {/* 拖拽提示信息 */}
      <div className={styles.dragHint}>
        <div className={styles.hintIcon}>🖱️</div>
        <div className={styles.hintText}>
          {canDrop ? '拖拽到目标位置并松开' : '移动到可用位置'}
        </div>
      </div>

      {/* 磁吸效果指示器 */}
      {dropTarget && dropTarget.isValid && (
        <div className={styles.snapIndicator}>
          <div className={styles.snapRing} />
          <div className={styles.snapDot} />
        </div>
      )}
    </div>
  );
};

export default EnhancedDragPreview;
